import {
  Breadcrumb,
  Form,
  Button,
  Radio,
  Input,
  Upload,
  Space,
  Select
} from 'antd'
import { PlusOutlined } from '@ant-design/icons'
import { Link, useSearchParams } from 'react-router-dom'
import ReactQuill from 'react-quill'
import 'react-quill/dist/quill.snow.css'
import request from '@/service/request'
import './index.scss'
import { useEffect, useRef, useState } from 'react'

const { Option } = Select

const Publish = () => {
  // 获取频道
  const [channels, setChannels] = useState([])
  useEffect(() => {
    async function fetchChannels () {
      const res = await request.get('/channels')
      setChannels(res.data.channels)

    }
    fetchChannels()
  }, [])

  // 获取路由参数

  const [params] = useSearchParams()
  const articleId = params.get('id')

  // 根据文章id获取详情信息

  useEffect(() => {
    async function getArticle () {
      // const res = await request.get(`/mp/articles/${articleId}`)
      // const { cover, ...formValue } = res.data
      // 动态设置表单数据
      // form.setFieldsValue({ ...formValue, type: cover.type })
    }
    if (articleId) {
      // 拉取数据回显
      getArticle()
    }
  }, [articleId])

  // 上传图片
  const [fileList, setFileList] = useState([])
  // 暂存仓库
  const cacheImgList = useRef()
  // 上传成功回调
  const onUploadChange = info => {
    const fileList = info.fileList.map(file => {
      if (file.response) {
        return {
          url: file.response.data.url
        }
      }
      return file
    })
    setFileList(fileList)
    cacheImgList.current = fileList
    console.log(cacheImgList.current)
  }

  // 切换图片
  const [imgCount, setImgCount] = useState(1)
  const changeType = (e) => {
    const count = e.target.value
    setImgCount(count)
    if (count === 1) {
      console.log(cacheImgList.current)
      const img = cacheImgList.current[0]
      setFileList([img])
    } else if (count === 3) {
      const imgs = cacheImgList.current ? cacheImgList.current : []
      setFileList(imgs)
    }
  }

  const onFinish = async (values) => {
    const { type, ...rest } = values
    const data = {
      ...rest,
      // 注意：接口会按照上传图片数量来决定单图 或 三图
      cover: {
        type,
        images: fileList.map(item => item.url)
      }
    }
    if (articleId) {
      // 编辑
      await request.put(`/mp/articles/${data.id}?draft=false`, data)
    } else {
      // 新增
      await request.post('/mp/articles?draft=false', data)
    }
  }


  return (
    <div className="publish">
      <Breadcrumb separator=">">
        <Breadcrumb.Item>
          <Link to="/home">首页</Link>
        </Breadcrumb.Item>
        <Breadcrumb.Item> {articleId ? '修改文章' : '发布文章'}</Breadcrumb.Item>
      </Breadcrumb>
      <Form
        labelCol={{ span: 1 }}
        wrapperCol={{ span: 16 }}
        initialValues={{ type: 1, content: '' }}
        onFinish={onFinish}
      >
        <Form.Item
          label="标题"
          name="title"
          rules={[{ required: true, message: '请输入文章标题' }]}
        >
          <Input placeholder="请输入文章标题" style={{ width: 400 }} />
        </Form.Item>
        <Form.Item
          label="频道"
          name="channel_id"
          rules={[{ required: true, message: '请选择文章频道' }]}
        >
          <Select placeholder="请选择文章频道" style={{ width: 400 }}>
            {channels.map(item => (
              <Option key={item.id} value={item.id}>
                {item.name}
              </Option>
            ))}
          </Select>
        </Form.Item>

        <Form.Item label="封面">
          <Form.Item name="type">
            <Radio.Group onChange={changeType}>
              <Radio value={1}>单图</Radio>
              <Radio value={3}>三图</Radio>
              <Radio value={0}>无图</Radio>
            </Radio.Group>
          </Form.Item>
          {
            imgCount > 0 && (
              <Upload
                name="image"
                listType="picture-card"
                className="avatar-uploader"
                showUploadList
                action="http://geek.itheima.net/v1_0/upload"
                fileList={fileList}
                onChange={onUploadChange}
                maxCount={imgCount}
                multiple={imgCount > 1}
              >
                <div style={{ marginTop: 8 }}>
                  <PlusOutlined />
                </div>
              </Upload>
            )
          }
        </Form.Item>
        <Form.Item
          label="内容"
          name="content"
          rules={[{ required: true, message: '请输入文章内容' }]}
        >
          <ReactQuill
            className="publish-quill"
            theme="snow"
            placeholder="请输入文章内容"
          />
        </Form.Item>

        <Form.Item wrapperCol={{ offset: 4 }}>
          <Space>
            <Button size="large" type="primary" htmlType="submit">
              {articleId ? '修改文章' : '发布文章'}
            </Button>
          </Space>
        </Form.Item>
      </Form>
    </div >
  )
}

export default Publish